from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from rest_framework.decorators import action

from .models import User
from . import serializers
from . import constants
# Create your views here.


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """收货地址：增删改查"""

    # 指定序列化器
    serializer_class = serializers.UserAddressSerializer
    # 指定权限
    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        """实现地址新增"""

        # 判断用户地址数量是否超过上线
        count = request.user.addresses.count()
        # count = Address.objects.filter(user=request.user).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        # 调用父类的create()方法实现以下逻辑
        return super().create(request, *args, **kwargs)

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """验证邮箱"""

    def get(self, request):
        # 读取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message':'缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证出token中的user信息(核心代码)
        user = User.check_verify_email_token(token)
        if not user:
            return Response({'message':'token 无效'}, status=status.HTTP_400_BAD_REQUEST)

        # 将user的email_active字段设置为True （核心思想）
        user.email_active = True
        user.save()

        return Response({'message':'OK'})


class EmailView(UpdateAPIView):
    """添加、更新邮箱"""
    serializer_class = serializers.EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# url(r'^user/$', views.UserDetailView.as_view()),
class UserDetailView(RetrieveAPIView):
    """个人中心基本信息"""
    # 指定序列化器类
    serializer_class = serializers.UserDetailSerializer
    # 指定权限，只有登录用户可以访问
    permission_classes = [IsAuthenticated]

    # 指定查询集
    # queryset = User.objects.all()
    def get_object(self):
        """重写该方法，返回序列化器要序列化的登录用户信息"""
        # 只要视图中加了IsAuthenticated权限，self.request.user出来的结果，一定是登录用户信息
        return self.request.user

"""
class RetrieveModelMixin(object):
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
"""


# url(r'^users/$', views.UserView.as_view()),
class UserView(CreateAPIView):
    """注册"""
    # 指定序列化器类
    serializer_class = serializers.UserSerializer


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """判断手机号是否重复注册"""

    def get(self, request, mobile):

        # 用username作为条件查询该记录是否存在
        count = User.objects.filter(mobile=mobile).count()

        # 序列化：模型数据转字典
        data = {
            'mobile':mobile,
            'count':count
        }

        # 响应结果
        return Response(data)


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """判断用户名是否重复注册"""

    def get(self, request, username):

        # 用username作为条件查询该记录是否存在
        count = User.objects.filter(username=username).count()

        # 序列化：模型数据转字典
        data = {
            'username':username,
            'count':count
        }

        # 响应结果
        return Response(data)
